package com.foreveross.project.usercenterserver.config;

import com.alibaba.fastjson.JSON;
import com.foreveross.project.usercenterserver.common.constant.ResultCode;
import com.foreveross.project.usercenterserver.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import springfox.documentation.swagger.web.UiConfiguration;

/**
 * 统一处理返回数据包装
 */
@Aspect
@RestControllerAdvice(basePackages = {"com.foreveross.project","org.springframework.security"})
//@RestControllerAdvice(basePackages = "org.springframework.security")
//@RestControllerAdvice
@Slf4j
public class DataResponseWrapper implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (o instanceof R) {
            return o;
        } else if (o instanceof String) {
            return JSON.toJSONString(R.ok(o));
        } else if (o instanceof OAuth2Exception) {//TODO 这里有问题
            log.error("授权失败");
            return R.error(ResultCode.UNAUTHORIZED.getCode(), ((OAuth2Exception) o).getMessage());
        } else {
            return R.ok(o);
        }
    }


}
